package com.java.controller;

import com.java.client.CoreFeignClient;
import com.java.exceptioin.Assert;
import com.java.result.ResponseEnum;
import com.java.result.Result;
import com.java.service.SmsService;
import com.java.sms.utils.SmsProperties;
import com.java.utils.RandomUtil;
import com.java.utils.RegexValidateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api("发送短信")
@RestController
@RequestMapping("/api/sms")
public class SmsController {

    private static final Logger log = LoggerFactory.getLogger(SmsController.class);
    @Resource
    private SmsService smsService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private CoreFeignClient coreFeignClient;

    @ApiOperation("发送短信验证码")
    @GetMapping("/send/{phone}")
    public Result send(@PathVariable String phone){

        //校验手机号
        Assert.notNull(phone,ResponseEnum.MOBILE_NULL_ERROR);
        Assert.isTrue(RegexValidateUtils.checkCellphone(phone),ResponseEnum.MOBILE_ERROR);
        //注册时校验手机号时候存在
        Boolean aBoolean = coreFeignClient.checkPhone(phone);
        log.info("phone："+aBoolean);
        Assert.isTrue(!aBoolean,ResponseEnum.MOBILE_EXIST_ERROR);

        Map<String, Object> map = new HashMap<>();
        //生成随机随机四位数验证码
        String code =RandomUtil.getFourBitRandom();
        map.put("code",code);
        smsService.send(phone, SmsProperties.TEMPLATE_CODE,map);
        redisTemplate.opsForValue().set("srb:sms:code:"+phone,code,1, TimeUnit.MINUTES);
        return Result.ok(code);
    }
}
